package com.xiaoxi.bms.common.util;

import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaoxi.bms.common.constant.enumeration.statuscode.system.FileSystemEnums;
import com.xiaoxi.bms.common.exception.BMSException;
import com.xiaoxi.bms.domain.common.FastDfs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.InputStreamResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author xiaoxi
 * @ProjectName springcloudbms
 * @PackageName com.xiaoxi.fastdfs.util
 * @ClassName FastDfsUtils
 * @Description TODO
 * @Date 2023/2/9 18:55
 * @Version 1.0
 */
@Slf4j
public class FastDfsUtils {

    /**
     * 上传文件 核心
     *
     * @param file
     * @param suffix
     * @param directory
     * @return
     * @throws BMSException
     */
    public static FastDfs upload(MultipartFile file, String suffix, String directory, String url) throws BMSException {

        InputStreamResource isr = null;
        try {

            isr = new InputStreamResource(file.getInputStream(), file.getOriginalFilename());

            String uuid = UUIDUtils.getRandomUUID();
            String newFileName = uuid + suffix;
            Map<String, Object> params = new HashMap<>();
            params.put("file", isr);
            params.put("scene", directory);
            params.put("filename", newFileName);
            params.put("output", "json");

            String resp = HttpUtil.post(url, params);

            log.info("json : {}", resp);

            ObjectMapper objectMapper = new ObjectMapper();

            return objectMapper.readValue(resp, FastDfs.class);

        } catch (IOException ioException) {
            log.error("输出流出现异常：{}", ioException.getMessage());
            throw new BMSException(FileSystemEnums.FILE_STREAM_ERROR);
        }
    }

}
